package net.hn.hnms.sys.common.satoken.config;

import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


/**
 * 智呈物联 pan'sx
 * 2022/11/29 9:51
 * 1.0 version
 */
@Aspect
@Component
public class SetMineCode {

    @Around(value = "@annotation(net.hn.hnms.sys.common.satoken.config.AutoSetMineCode)")
    public Object setMineCode(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        parameter:
        for (int i = 0; i < parameterNames.length; i++) {
            if (args[i] instanceof String || args[i] == null) {
                if ("mineCode".equals(parameterNames[i])||"companyCode".equals(parameterNames[i])) {
                    if (args[i] == null || StringUtils.isBlank(args[i].toString())) {
                        LoginUser loginUser = LoginHelper.getLoginUser();
//                        if (loginUser.getContainOrgs().isEmpty()) {//如果下面有子煤矿证明是公司或集团级  不设置，controller层自行处理
                            args[i] = loginUser.getOrganizationCode();
                            break parameter;
//                        }
                    }
                }
            } else if (args[i] instanceof Object) {//接收参数是对象时适用
                Class classObj = (Class) args[i].getClass();
                if(classObj.getPackage()==null) continue;
                if (!classObj.getPackage().getName().contains("net.hn")) continue;
                Field[] fields = classObj.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (("mineCode".equals(field.getName())||"companyCode".equals(field.getName()) )&& field.getType() == String.class && StringUtils.isBlank((String) field.get(args[i]))) {
                        LoginUser loginUser = LoginHelper.getLoginUser();
//                        if (loginUser.getContainOrgs().isEmpty()) {//如果下面有子煤矿证明是公司或集团级  不设置，controller层自行处理
                            field.set(args[i], loginUser.getOrganizationCode());
                            break parameter;
//                        }

                    }
                }
            }

        }
        return joinPoint.proceed(args);
    }
}
